package com.wstuo.itsm;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.Dispatcher;

/**
 * 客户端请求过滤
 * @author Ciel
 *
 */
public class ResponseHeaderFilter implements StrutsStatics, Filter {
	private static final Logger LOGGER = Logger.getLogger(ResponseHeaderFilter.class);
	protected Dispatcher dispatcher;
	private Map<String,String> params = new HashMap<String,String>();
	FilterConfig fc;

	public void destroy() {
		this.fc = null;

	}

	@SuppressWarnings("rawtypes")
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		try {
			HttpServletResponse res = (HttpServletResponse) response;

			for (String key:params.keySet()) {
				res.addHeader(key, params.get(key));
			}
			chain.doFilter(request, res);
		} catch (Exception e) {
			LOGGER.error(e);
		}

	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.fc = filterConfig;
		
		for (Enumeration e = filterConfig.getInitParameterNames(); e
				.hasMoreElements();) {
			String name = (String) e.nextElement();
			String value = filterConfig.getInitParameter(name);
			params.put(name, value);
		}
		dispatcher = new Dispatcher(filterConfig.getServletContext(), params);

		filterConfig.getServletContext().setAttribute("STRUTS_DISPATCHER",
				dispatcher);
	}

}
